<template>
  <div class="register-container">
    <el-card class="register-card">
      <div class="register-header">
        <h2>用户注册</h2>
      </div>
      <el-form :model="registerForm" :rules="rules" class="register-form">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号码" prop="phoneNumber">
          <el-input v-model="registerForm.phoneNumber" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="registerForm.address" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="register-button" @click="handleRegister" :loading="loading">
            注册
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" :underline="false" @click="handleLogin">已有账号，去登录</el-link>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { authService } from '../services/authService'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '../store'

const router = useRouter()

// 注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
  phoneNumber: '',
  address: ''
})

// 加载状态
const loading = ref(false)

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  phoneNumber: [
    { required: false, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码格式', trigger: 'blur' }
  ],
  address: [
    { required: false, message: '请输入地址', trigger: 'blur' },
    { max: 500, message: '地址长度不能超过500个字符', trigger: 'blur' }
  ]
}

// 处理注册
const handleRegister = async () => {
  // 模拟表单验证
  if (!registerForm.username) {
    ElMessage.error('请输入用户名')
    return
  }
  if (registerForm.username.length < 4 || registerForm.username.length > 20) {
    ElMessage.error('用户名长度必须在4-20个字符之间')
    return
  }
  if (!registerForm.password) {
    ElMessage.error('请输入密码')
    return
  }
  if (registerForm.password.length < 6 || registerForm.password.length > 20) {
    ElMessage.error('密码长度必须在6-20个字符之间')
    return
  }
  if (registerForm.password !== registerForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  if (!registerForm.email) {
    ElMessage.error('请输入邮箱')
    return
  }
  if (registerForm.address && registerForm.address.length > 500) {
    ElMessage.error('地址长度不能超过500个字符')
    return
  }
  
  try {
    loading.value = true
    console.log('Register: 开始注册流程', registerForm)
    // 调用注册接口
    const result = await authService.register(registerForm)
    console.log('Register: 注册结果', result)
    
    if (result && result.token) {
      // 保存注册结果到store
      const userStore = useUserStore()
      userStore.saveLoginResult(result)
      
      ElMessage.success('注册成功，正在跳转到首页')
      // 注册成功后跳转到首页
      setTimeout(() => {
        router.push('/')
      }, 1500)
    } else {
      ElMessage.error('注册失败，请稍后重试')
    }
  } catch (error) {
    console.error('Register: 注册失败', error)
    
    // 检查是否有自定义错误消息
    let errorMessage = '注册失败，请稍后重试'
    if (error.customMessage) {
      errorMessage = error.customMessage
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 处理登录
const handleLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f5f5;
}

.register-card {
  width: 450px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-radius: 8px;
}

.register-header {
  text-align: center;
  margin-bottom: 20px;
}

.register-header h2 {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.register-form {
  padding: 20px;
}

.register-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item__label {
  font-size: 14px;
  color: #666;
}

.el-input {
  width: 100%;
}

.el-link {
  float: right;
}
</style>